package com.xiangban.yanglaodajie_platform.controller;

import com.alibaba.fastjson.JSON;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import com.xiangban.yanglaodajie_platform.entity.res.ApiResult;
import com.xiangban.yanglaodajie_platform.service.AccumulatePointsService;
import com.xiangban.yanglaodajie_platform.service.PayService;
import com.xiangban.yanglaodajie_platform.utils.WXConfigUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;

@Controller
@RequestMapping("api/pay")
public class PayController {
    protected final static Logger logger = LoggerFactory.getLogger(PayController.class);
    @Autowired
    private PayService payService;

    @Autowired
    private AccumulatePointsService accumulatePointsService;

    @PostMapping(value ="/wxPay")
    @ResponseBody
    public ApiResult<Object> WxPay() {
        return null;
//        try {
//            payService.doUnifiedOrder();
//            return ApiResult.newSuccess(payService.doUnifiedOrder());
//        } catch (Exception e) {
//            logger.error("微信支付接口失败 error : {}");
//            e.printStackTrace();
//            return ApiResult.newSuccess("微信支付数据失败----->" + e.getMessage());
//        }

    }

    @RequestMapping(value = "/wxPayNotify")
    @ResponseBody
    public String wxPayNotify(HttpServletRequest request) {
        String resXml = "";
        try {
            InputStream inputStream = request.getInputStream();
            // 将InputStream转换成xmlString
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder sb = new StringBuilder();
            String line = null;
            try {
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
            } catch (IOException e) {
                System.out.println(e.getMessage());
            } finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            resXml = sb.toString();
            String result = payService.payBack(resXml);
            WXConfigUtil config = new WXConfigUtil();
            WXPay wxpay = new WXPay(config);
            Map<String, String> notifyMap = WXPayUtil.xmlToMap(resXml);
            // 调用官方SDK转换成map类型数据
            if (wxpay.isPayResultNotifySignatureValid(notifyMap)) {
                // 验证签名是否有效
                String return_code = notifyMap.get("return_code");// 状态
                String out_trade_no = notifyMap.get("out_trade_no");// 商户订单号
                if (return_code.equals("SUCCESS")) {
                    if (out_trade_no != null) {
                        logger.info("===================回调成功===========");
                        accumulatePointsService.updateTransaction(out_trade_no);
                        logger.info(JSON.toJSONString(notifyMap));
                        logger.info("=======成功返回报文========"+JSON.toJSONString(result));
                    }
                }
            }
            return result;

        } catch (Exception e) {
            logger.error("微信回调接口失败 error : {}", e);
            e.printStackTrace();
            String result = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                    + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
            logger.error(result);
            return result;
        }
    }
}
